<template>
    <!--加工验收修改 -->
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="验收明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="服务费用"
                    name="transportationCharge"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        ref="formDataRef"
                                        :rules="formDataRules"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收编号"
                                                    prop="billNo"
                                                >
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="所属机构"
                                                    prop="orgName"
                                                >
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="收料类型"
                                                    prop="receivingType"
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formData.receivingType
                                                        "
                                                        :disabled="
                                                            formData.redBillState ==
                                                            3
                                                        "
                                                        @change="
                                                            receivingTypeChange
                                                        "
                                                    >
                                                        <el-radio :label="0"
                                                            >普通加工</el-radio
                                                        >
                                                        <el-radio :label="1"
                                                            >砼加工</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收日期"
                                                    prop="acceptanceDate"
                                                >
                                                    <el-date-picker
                                                        v-model="
                                                            formData.acceptanceDate
                                                        "
                                                        type="date"
                                                        placeholder="选择日期"
                                                        value-format="yyyy-MM-dd"
                                                        :clearable="false"
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                    </el-date-picker>
                                                    <span v-else>{{
                                                        formData.acceptanceDate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="是否计加工费"
                                                    prop="isIncludingProcessingFee"
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formData.isIncludingProcessingFee
                                                        "
                                                        :disabled="
                                                            formData.redBillState ==
                                                            3
                                                        "
                                                    >
                                                        <el-radio :label="1"
                                                            >是(外部加工)</el-radio
                                                        >
                                                        <el-radio :label="0"
                                                            >否(自行加工)</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="采购人员"
                                                    prop="purchaserName"
                                                >
                                                    {{ formData.purchaserName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="加工单位"
                                                    prop="processingUnitName"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formData.processingUnitName
                                                        "
                                                        readonly
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                processingUnitNameClick
                                                            "
                                                        ></i>
                                                    </el-input>
                                                    <span v-else>{{
                                                        formData.processingUnitName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <!-- 是否计加工费的值为: 是(外部加工,才显示该字段) -->
                                                <el-form-item
                                                    label="加工合同"
                                                    v-show="
                                                        formData.isIncludingProcessingFee
                                                    "
                                                >
                                                    <span>
                                                        {{
                                                            formData.contractName
                                                        }}
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                contractNoClick
                                                            "
                                                            v-show="
                                                                formData.contractName
                                                            "
                                                        ></i>
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.taxRate
                                                        "
                                                        @input.native="
                                                            onInput0_100
                                                        "
                                                        v-enter-float="{
                                                            set: formData,
                                                            key: 'taxRate'
                                                        }"
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    ></el-input>
                                                    <span v-else>{{
                                                        formData.taxRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收人员"
                                                    prop="acceptancerName"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formData.acceptancerName
                                                        "
                                                        readonly
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                acceptancerNameClick
                                                            "
                                                        ></i>
                                                    </el-input>
                                                    <span v-else>{{
                                                        formData.acceptancerName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 汇总验收明细的清单税额累计 -->
                                                <el-form-item
                                                    label="税额"
                                                    prop="taxAmount"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.taxAmount
                                                        "
                                                        v-if="
                                                            formData.redBillState !=
                                                            3
                                                        "
                                                        v-enter-float="{
                                                            set: formData,
                                                            key: 'taxAmount'
                                                        }"
                                                    ></el-input>
                                                    <span v-else>{{
                                                        formData.taxAmount
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="服务费用(元)"
                                                    prop="freight"
                                                >
                                                    {{ formData.freight }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 收料类型为【普通加工】显示“原材料来源” -->
                                                <el-form-item
                                                    label="原材料来源"
                                                    :prop="
                                                        !formData.receivingType
                                                            ? 'sourceOfRawMaterials'
                                                            : 'sourceOfRawMaterialss'
                                                    "
                                                    v-show="
                                                        !formData.receivingType
                                                    "
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formData.sourceOfRawMaterials
                                                        "
                                                        :disabled="
                                                            formData.redBillState ==
                                                            3
                                                        "
                                                    >
                                                        <el-radio :label="1"
                                                            >购买</el-radio
                                                        >
                                                        <el-radio :label="2"
                                                            >自有</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="加工验收金额(元)"
                                                    prop="acceptanceAmount"
                                                >
                                                    {{
                                                        formData.acceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税价合计"
                                                    prop="totalAmount"
                                                >
                                                    <!-- <el-input
                                    placeholder="请填写"
                                    v-model="formData.totalAmount"
                                ></el-input> -->
                                                    {{ formData.totalAmount }}
                                                    元
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                    <el-select
                                                        v-model="
                                                            formData.currencyId
                                                        "
                                                        placeholder="请选择"
                                                        v-if="
                                                            !formData.isIncludingProcessingFee &&
                                                            formData.redBillState !=
                                                                3
                                                        "
                                                        @change="currencyChange"
                                                    >
                                                        <el-option
                                                            v-for="item in currencyForm"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                    <span v-else>{{
                                                        formData.currency
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{ formData.baseCurName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurRate"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.baseCurRate
                                                        "
                                                        v-enter-float2="{
                                                            set: formData,
                                                            key: 'baseCurRate'
                                                        }"
                                                        v-if="
                                                            !isBaseCurRate &&
                                                            formData.redBillState !=
                                                                3
                                                        "
                                                        @blur="baseCurRateBlur"
                                                    ></el-input>
                                                    <span v-else>{{
                                                        formData.baseCurRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <!-- <el-col :span="12">
                                                <el-form-item
                                                    label="验收金额(本位币)"
                                                    prop="baseCurAcceptanceAmount"
                                                >
                                                    {{
                                                        formData.baseCurAcceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col> -->
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="状态"
                                                    prop="state"
                                                >
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享"
                                                    prop=""
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col
                                                :span="12"
                                                v-if="
                                                    formData.redBillState !== -1
                                                "
                                            >
                                                <el-form-item label="冲红单">
                                                    <span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注">
                                                <el-input
                                                    v-model="formData.remarks"
                                                    type="textarea"
                                                    :rows="2"
                                                    resize="none"
                                                    placeholder="请输入内容"
                                                    maxlength='500'
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 验收明细 -->

                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            验收明细
                        </div>

                        <!-- 验收明细的tab标签页 -->
                        <div class="tabs-content">
                            <el-tabs
                                v-model="acceptanceDetailsTabs"
                                :class="'childTab ' + childTabClass"
                                tab-position="left"
                                @tab-click="onChangeTab"
                            >
                                <el-tab-pane
                                    label="加工费"
                                    name="processingFee"
                                    :disabled="clickTabFlag"
                                ></el-tab-pane>
                                <el-tab-pane
                                    label="成品明细"
                                    name="finishedProductDetails"
                                    :disabled="clickTabFlag"
                                ></el-tab-pane>
                                <el-tab-pane
                                    label="原物资"
                                    name="rawMaterials"
                                    :disabled="clickTabFlag"
                                ></el-tab-pane>
                                <div>
                                    <div id="receivingMaterialsCon">
                                        <div
                                            class="tabs-title"
                                            id="processingFee"
                                        >
                                            加工费
                                        </div>
                                        <div class="e-table">
                                            <div
                                                class="errorMsg"
                                                v-if="
                                                    errorProcessingFeeMsg.length >
                                                    0
                                                "
                                            >
                                                <span>
                                                    {{
                                                        errorProcessingFeeMsg.join(
                                                            ','
                                                        )
                                                    }}
                                                </span>
                                            </div>
                                            <el-table
                                                :data="processingFeeData"
                                                ref='processingFeeTable'
                                                border
                                                style="width: 100%"
                                                @cell-mouse-enter="
                                                    cellMouseEnter
                                                "
                                                @cell-mouse-leave="
                                                    cellMouseLeave
                                                "
                                                :cell-class-name="cellClsNm"
                                                :row-class-name="
                                                    tableRowClassNameJ
                                                "
                                                :header-cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren'
                                                }"
                                                row-key="uuid"
                                                :max-height="$store.state.tableHeight"
                                                v-sortTable="{ 'tableData': processingFeeData, '_this': this, 'ref': 'processingFeeTable' }"
                                            >
                                                <!-- <el-table-column
                                                    type="selection"
                                                    width="55"
                                                    fixed
                                                    v-if="
                                                        formData.redBillState !=
                                                        3
                                                    "
                                                >
                                                </el-table-column> -->
                                                <el-table-column
                                                    prop="materialClassName"
                                                    label="物资类别"
                                                    min-width="200"
                                                    fixed
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialName"
                                                    label="物资名称"
                                                    width="150"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="spec"
                                                    label="规格"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="texture"
                                                    label="材质"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="unit"
                                                    label="单位"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="warehouseName"
                                                    label="仓库"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    label="数量"
                                                    width="100"
                                                >
                                                    <template v-slot="{ row }">
                                                        <el-input
                                                            v-model="
                                                                row.quantity
                                                            "
                                                            v-enter-float2="{
                                                                set: row,
                                                                key: 'quantity'
                                                            }"
                                                            placeholder=""
                                                            @blur="
                                                                quantityInput(
                                                                    row
                                                                )
                                                            "
                                                            v-if="
                                                                !row.children &&
                                                                formData.redBillState !=
                                                                    3
                                                            "
                                                        ></el-input>
                                                        <span v-else>{{
                                                            row.quantity
                                                        }}</span>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="price"
                                                    label="加工单价（元）"
                                                    width="130"
                                                >
                                                </el-table-column>

                                                <el-table-column
                                                    prop="amount"
                                                    label="金额（元）"
                                                    width="130"
                                                >
                                                    <template v-slot="{ row }">
                                                        <el-input
                                                            v-model="row.amount"
                                                            v-enter-float="{
                                                                set: row,
                                                                key: 'amount'
                                                            }"
                                                            placeholder=""
                                                            @blur="
                                                                amountBlur(row)
                                                            "
                                                            v-if="
                                                                !row.children &&
                                                                formData.redBillState !=
                                                                    3
                                                            "
                                                        ></el-input>
                                                        <span v-else>{{
                                                            row.amount
                                                        }}</span>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                    <div id="receivingMaterialsCon">
                                        <div
                                            class="tabs-title"
                                            id="finishedProductDetails"
                                        >
                                            成品明细
                                        </div>
                                        <div class="e-table">
                                            <div
                                                class="errorMsg"
                                                v-if="
                                                    errorFinishedProductMsg.length >
                                                    0
                                                "
                                            >
                                                <span>
                                                    {{
                                                        errorFinishedProductMsg.join(
                                                            ','
                                                        )
                                                    }}
                                                </span>
                                            </div>
                                            <el-table
                                                :data="finishedProductData"
                                                ref='finishedProductTable'
                                                border
                                                style="width: 100%"
                                                @cell-mouse-enter="
                                                    cellMouseEnter
                                                "
                                                @cell-mouse-leave="
                                                    cellMouseLeave
                                                "
                                                :cell-class-name="cellClsNm"
                                                :row-class-name="
                                                    tableRowClassNameC
                                                "
                                                :header-cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren'
                                                }"
                                                row-key="uuid"
                                                :max-height="$store.state.tableHeight"
                                                v-sortTable="{ 'tableData': finishedProductData, '_this': this, 'ref': 'finishedProductTable' }"
                                            >
                                                <!-- <el-table-column
                                                    type="selection"
                                                    width="55"
                                                    fixed
                                                    v-if="
                                                        formData.redBillState !=
                                                        3
                                                    "
                                                >
                                                </el-table-column> -->
                                                <el-table-column
                                                    prop="materialClassName"
                                                    label="物资类别"
                                                    min-width="200"
                                                    fixed
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialName"
                                                    label="物资名称"
                                                    width="150"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="spec"
                                                    label="规格"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="texture"
                                                    label="材质"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="unit"
                                                    label="单位"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="warehouseName"
                                                    label="仓库"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="quantity"
                                                    label="数量"
                                                    width="100"
                                                >
                                                    <template v-slot="{ row }">
                                                        <el-input
                                                            v-model="
                                                                row.quantity
                                                            "
                                                            v-enter-float2="{
                                                                set: row,
                                                                key: 'quantity'
                                                            }"
                                                            placeholder=""
                                                            @blur="
                                                                finishedProductQuantityInput(
                                                                    row
                                                                )
                                                            "
                                                            v-if="
                                                                !row.children &&
                                                                formData.redBillState !=
                                                                    3
                                                            "
                                                        ></el-input>
                                                        <span v-else>{{
                                                            row.quantity
                                                        }}</span>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="price"
                                                    label="成品单价（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="amount"
                                                    label="金额（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="apportionedFreight"
                                                    label="分摊服务费（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="totalAmortizationRatio"
                                                    label="总摊销比例%"
                                                    width="130"
                                                    v-if='isZhoucai'
                                                >
                                                    <template v-slot="{ row }">
                                                        <!-- 成品为周材才显示 -->
                                                        <div
                                                            v-if="
                                                                row.materialType ==
                                                                1
                                                            "
                                                        >
                                                            <el-input
                                                                v-model="
                                                                    row.totalAmortizationRatio
                                                                "
                                                                v-enter-float="{
                                                                    set: row,
                                                                    key: 'totalAmortizationRatio'
                                                                }"
                                                                @input.native="
                                                                    onInput0_100
                                                                "
                                                                placeholder=""
                                                                @blur="
                                                                    totalAmortizationRatioBlur(
                                                                        row
                                                                    )
                                                                "
                                                                v-if="
                                                                    !row.children &&
                                                                    formData.redBillState !=
                                                                        3
                                                                "
                                                            ></el-input>
                                                            <span v-else>{{
                                                                row.totalAmortizationRatio
                                                            }}</span>
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="amortizationMonth"
                                                    label="摊销月"
                                                    width="100"
                                                    v-if='isZhoucai'
                                                >
                                                    <template v-slot="{ row }">
                                                        <!-- 成品为周材才显示 -->
                                                        <div
                                                            v-if="
                                                                row.materialType ==
                                                                1
                                                            "
                                                        >
                                                            <el-input
                                                                v-model="
                                                                    row.amortizationMonth
                                                                "
                                                                v-enter-float="{
                                                                    set: row,
                                                                    key: 'amortizationMonth'
                                                                }"
                                                                placeholder=""
                                                                @blur="
                                                                    amortizationMonthBlur(
                                                                        row
                                                                    )
                                                                "
                                                                v-if="
                                                                    !row.children &&
                                                                    formData.redBillState !=
                                                                        3
                                                                "
                                                            ></el-input>
                                                            <span v-else>{{
                                                                row.amortizationMonth
                                                            }}</span>
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                    <div id="receivingMaterialsCon">
                                        <div
                                            class="tabs-title"
                                            id="rawMaterials"
                                        >
                                            原物资
                                        </div>
                                        <div class="e-table">
                                            <div
                                                class="top"
                                                v-if="
                                                    formData.redBillState !=
                                                        3 &&
                                                    formData.receivingType === 0
                                                "
                                            >
                                                <div class="left">
                                                    <div>
                                                        <!-- <el-button
                                                            size="mini"
                                                            class="btn-blue"
                                                            @click="selectStock"
                                                            v-show="
                                                                formData.receivingType
                                                            "
                                                            >选择库存</el-button
                                                        > -->
                                                        <!-- 如果是普通加工,才可以选择库存,砼加工是自动带入原物资数据,砼加工必带入原物资 -->
                                                        <!-- 如果是普通加工,且原料来源是购买,必选原物资 -->
                                                        <!-- 如果是普通加工,原料来源是自有,且成品明细中物资类别包含周材,则必选原物资 -->
                                                        <el-dropdown
                                                            class="drp"
                                                            trigger="click"
                                                            @command="
                                                                selectStock
                                                            "
                                                        >
                                                            <el-button
                                                                class="btn-blue"
                                                            >
                                                                {{
                                                                    selectStocked
                                                                }}<i
                                                                    class="
                                                                        el-icon-arrow-down
                                                                        el-icon--right
                                                                    "
                                                                ></i>
                                                            </el-button>
                                                            <el-dropdown-menu
                                                                slot="dropdown"
                                                            >
                                                                <el-dropdown-item
                                                                    v-for="item in inStockList"
                                                                    :key="
                                                                        item.materialId
                                                                    "
                                                                    :command="
                                                                        item
                                                                    "
                                                                    >{{
                                                                        item.materialName
                                                                    }}</el-dropdown-item
                                                                >
                                                            </el-dropdown-menu>
                                                        </el-dropdown>
                                                        <el-button
                                                            size="mini"
                                                            class="btn-delete"
                                                            @click="
                                                                rawMaterialsDeleteClick
                                                            "
                                                            >批量删除</el-button
                                                        >
                                                    </div>
                                                    <!-- <div
                                                        class="batchBox"
                                                        @click="
                                                            batchOperation(
                                                                'rawMaterials'
                                                            )
                                                        "
                                                    >
                                                        <img
                                                            class="batchicon"
                                                            src="@/assets/piliang.png"
                                                        />
                                                        <span
                                                            class="batchfont"
                                                            >{{
                                                                isBatch[0].batch
                                                            }}</span
                                                        >
                                                    </div> -->
                                                </div>
                                            </div>
                                            <div
                                                class="errorMsg"
                                                v-if="
                                                    errorRawMaterialsMsg.length >
                                                    0
                                                "
                                            >
                                                <span>
                                                    {{
                                                        errorRawMaterialsMsg.join(
                                                            ','
                                                        )
                                                    }}
                                                </span>
                                            </div>
                                            <el-table
                                                :data="rawMaterialsData"
                                                border
                                                style="width: 100%"
                                                :row-class-name="
                                                    tableRowClassName
                                                "
                                                ref="rawMaterialsTable"
                                                @select='selectRow'
                                                @selection-change="rawMaterialsSelect"
                                                @select-all='rawMaterialsSelectAll'
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren'
                                                }"
                                                row-key="uuid"
                                                :class='tableHeadClass'
                                                :max-height="$store.state.tableHeight"
                                                v-sortTable="{ 'tableData': rawMaterialsData, '_this': this, 'ref': 'rawMaterialsTable' }"
                                            >
                                                <el-table-column
                                                    type="selection"
                                                    width="55"
                                                    v-if="
                                                        formData.redBillState !=
                                                            3 &&
                                                        formData.receivingType ===
                                                            0
                                                    "
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    label="操作"
                                                    fixed
                                                    width="100px"
                                                    align="left"
                                                    v-if="
                                                        formData.redBillState !=
                                                            3 &&
                                                        formData.receivingType ===
                                                            0
                                                    "
                                                >
                                                    <template
                                                        slot-scope="{
                                                            row,
                                                            $index
                                                        }"
                                                    >
                                                        <div
                                                            class="handle"
                                                            v-if="!row.children"
                                                        >
                                                            <div
                                                                style="
                                                                    cursor: pointer;
                                                                "
                                                                class="list_box"
                                                            >
                                                                <img
                                                                    src="@/assets/btn/delete.png"
                                                                    class="
                                                                        add_sub
                                                                    "
                                                                    title="删除"
                                                                    @click="
                                                                        rawMaterialsDelete(
                                                                            row,
                                                                            $index
                                                                        )
                                                                    "
                                                                />
                                                            </div>
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialClassName"
                                                    label="类别"
                                                    min-width="250"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialName"
                                                    label="物资名称"
                                                    min-width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="spec"
                                                    label="规格"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="texture"
                                                    label="材质"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="unit"
                                                    label="单位"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="warehouseName"
                                                    label="仓库"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="receivedQuantity"
                                                    label="领用数量"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="offsetInventoryQuantity"
                                                    label="冲库存数量"
                                                    width="130"
                                                >
                                                    <template v-slot="{ row }">
                                                        <el-input
                                                            v-model="
                                                                row.offsetInventoryQuantity
                                                            "
                                                            v-enter-float2="{
                                                                set: row,
                                                                key: 'offsetInventoryQuantity'
                                                            }"
                                                            placeholder=""
                                                            @blur="
                                                                offsetInventoryQuantityBlur(
                                                                    row
                                                                )
                                                            "
                                                            v-if="
                                                                !row.children &&
                                                                formData.redBillState !=
                                                                    3
                                                            "
                                                        ></el-input>
                                                        <span v-else>{{
                                                            row.offsetInventoryQuantity
                                                        }}</span>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column
                                                    prop="price"
                                                    label="采购单价（元）"
                                                    width="130"
                                                >
                                                </el-table-column>

                                                <el-table-column
                                                    prop="amount"
                                                    label="金额（元）"
                                                    width="130"
                                                >
                                                    <template v-slot="{ row }">
                                                        <el-input
                                                            v-model="row.amount"
                                                            v-enter-float="{
                                                                set: row,
                                                                key: 'amount'
                                                            }"
                                                            placeholder=""
                                                            @blur="
                                                                ywzAmountBlur(
                                                                    row
                                                                )
                                                            "
                                                            v-if="
                                                                !row.children &&
                                                                formData.redBillState !=
                                                                    3
                                                            "
                                                        ></el-input>
                                                        <span v-else>{{
                                                            row.amount
                                                        }}</span>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                </div>
                            </el-tabs>
                        </div>
                    </div>

                    <!-- 服务费用 -->
                    <div id="transportationChargeCon" class="con">
                        <div class="tabs-title" id="transportationCharge">
                            服务费用
                        </div>
                        <div class="e-table">
                            <div
                                class="top"
                                v-if="
                                    formData.redBillState != 3 &&
                                    finishedProductData.length > 0
                                "
                            >
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="mini"
                                            class="btn-blue"
                                            @click="addRowClick"
                                            >新增行</el-button
                                        >
                                        <el-button
                                            size="mini"
                                            class="btn-delete"
                                            @click="serviceFeeDeleteClick"
                                            >批量删除</el-button
                                        >
                                    </div>
                                    <!-- <div
                                        class="batchBox"
                                        @click="batchOperation('serviceFee')"
                                    >
                                        <img
                                            class="batchicon"
                                            src="@/assets/piliang.png"
                                        />
                                        <span class="batchfont">{{
                                            isBatch[1].batch
                                        }}</span>
                                    </div> -->
                                </div>
                            </div>
                            <div
                                class="errorMsg"
                                v-if="errorServiceFeeMsg.length > 0"
                            >
                                <span>
                                    {{ errorServiceFeeMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="serviceFeeData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassNameF"
                                @selection-change="serviceFeeSelect"
                                ref="serviceFeeTable"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': serviceFeeData, '_this': this, 'ref': 'serviceFeeTable' }"
                            >
                                <el-table-column
                                    type="selection"
                                    width="55"
                                    v-if="formData.redBillState != 3"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                    v-if="formData.redBillState != 3"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div
                                                style="cursor: pointer"
                                                class="list_box"
                                            >
                                                <img
                                                    src="@/assets/btn/delete.png"
                                                    class="add_sub"
                                                    title="删除"
                                                    @click="
                                                        serviceFeeDelete(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    label="合同编号"
                                    min-width="150"
                                >
                                    <template v-slot="{ row, $index }">
                                        {{ row.contractBillNo }}
                                        <i
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                            "
                                            class="el-icon-document-copy"
                                            @click="contractDialog(row, $index)"
                                            v-if="formData.redBillState != 3"
                                        ></i>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="结算单位"
                                    min-width="190"
                                >
                                    <template v-slot="{ row, $index }">
                                        {{ row.settlementUnitName }}
                                        <i
                                            style="
                                                cursor: pointer;
                                                font-size: 20px;
                                            "
                                            class="el-icon-document-copy"
                                            @click="
                                                billingUnitDialog(row, $index)
                                            "
                                            v-if="formData.redBillState != 3"
                                        ></i>
                                    </template>
                                </el-table-column>

                                <el-table-column
                                    prop="contractDtlName"
                                    label="清单名称"
                                    width="100"
                                >
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.contractDtlName"
                                            placeholder=""
                                            v-if="
                                                formData.redBillState != 3 &&
                                                !row.contractBillNo
                                            "
                                            @blur="contractDtlNameBlur(row)"
                                        ></el-input>
                                        <span v-else>{{
                                            row.contractDtlName
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" width="100">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.quantity"
                                            v-enter-float2="{
                                                set: row,
                                                key: 'quantity'
                                            }"
                                            placeholder=""
                                            @blur="quantityBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.quantity }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额(元)"
                                    width="100"
                                >
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.amount"
                                            v-enter-float="{
                                                set: row,
                                                key: 'amount'
                                            }"
                                            placeholder=""
                                            @blur="amountFBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.amount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="发票编号" width="130">
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.invoiceNo"
                                            v-enterInteger1
                                            placeholder=""
                                            @blur="invoiceNoBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.invoiceNo }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="taxRate"
                                    label="税率%"
                                    width="130"
                                >
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.taxRate"
                                            v-enter-float="{
                                                set: row,
                                                key: 'taxRate'
                                            }"
                                            @input.native="onInput0_100"
                                            placeholder=""
                                            @blur="taxRateBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.taxRate }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="taxAmount"
                                    label="税额(元)"
                                    width="130"
                                >
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.taxAmount"
                                            v-enter-float="{
                                                set: row,
                                                key: 'taxAmount'
                                            }"
                                            placeholder=""
                                            @blur="taxAmountBlur(row)"
                                            v-if="formData.redBillState != 3"
                                        ></el-input>
                                        <span v-else>{{ row.taxAmount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="totalAmount"
                                    label="税价合计(元)"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="materialsettle"
                            v-if="objFlag.flag5"
                            :isView="formData.redBillState != 3 ? false : true"
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AcceptanceHistory
                            :billType="1016"
                            :billId="billid"
                        ></AcceptanceHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 1 || formData.state == 9"
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 2 && formData.redBillState == -1"
                >冲红单</el-button
            >
            <exaButtons
                :auditState="auditState"
                @exas="exas"
                :state="formData.state"
                :founderId="formData.founderId"
            ></exaButtons>

            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {
    showPromptPop,
    showSuccessPop,
    showLoading,
    hideLoading,
    getUuid,
    openAppClient
} from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import processingRequest from '@/api/materials/processingAcceptance'
import request from '@/api/materials/materialAcceptance'
import exaButtons from '@/components/common/exaButtons'
import AcceptanceHistory from '@/pages/materialsmanagement/checkAdmin/AcceptanceHistory'

export default {
    components: {
        AttachComp,
        exaButtons,
        AcceptanceHistory
    },
    data () {
        return {
            tabsName: 'baseInfo',
            clickId: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                billNo: '', //验收编号
                orgName: '', //所属机构
                isIncludingProcessingFee: '', //是否计加工费
                acceptanceDate: '', //验收日期
                receivingType: '', //收料类型
                purchaserName: '', //采购人员
                processingUnitName: '', //加工单位
                acceptancerName: '', //验收人员
                taxRate: '', //税率%
                freight: '', //运输单位费用
                taxAmount: '', //税额
                currency: '', //币种
                acceptanceAmount: '', //加工验收金额
                showEas: '', //传财务共享
                totalAmount: '', //税价合计
                baseCurAcceptanceAmount: '', //验收金额(本位币)
                baseCurName: '', //本位币
                state: '', //状态
                remarks: '', //备注
                acceptanceQuantity: 0,
                acceptancerId: '',
                baseCurFreight: 0,
                baseCurId: '',
                baseCurRate: 0,
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                businessType: 0,
                currencyId: '',
                easId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                isAccepSettle: true,
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                purchaserId: '',
                purchasingUnitId: '',
                purchasingUnitName: '',
                redBillState: '',
                rmbAcceptanceAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settleId: '',
                settleNo: '',
                sourceBillId: '',
                sourceBillNo: '',
                sourceId: '',
                sourceNumber: '',
                supplierId: '',
                supplierName: '',
                workId: '',
                contractId: '',
                contractName: '',
                contractNo: '',
                processingUnitId: '',
                sourceOfRawMaterials: 0
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            formDataRules: {
                receivingType: [
                    {
                        required: true,
                        message: '请选择收料类型',
                        trigger: 'blur'
                    }
                ],
                // acceptanceDate: [
                //     {
                //         required: true,
                //         message: '请选择验收日期',
                //         trigger: 'blur'
                //     }
                // ],
                isIncludingProcessingFee: [
                    {
                        required: true,
                        message: '请选择是否计加工费',
                        trigger: 'blur'
                    }
                ],
                purchaserName: [
                    {
                        required: true,
                        message: '采购人员是必填项',
                        trigger: 'blur'
                    }
                ],
                processingUnitName: [
                    {
                        required: true,
                        message: '请选择加工单位',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    {
                        required: true,
                        message: '请填写税率',
                        trigger: 'blur'
                    }
                ],
                taxAmount: [
                    {
                        required: true,
                        message: '请填写税额',
                        trigger: 'blur'
                    }
                ],
                acceptanceAmount: [
                    {
                        required: true,
                        message: '加工验收金额为必填项',
                        trigger: 'blur'
                    }
                ],
                totalAmount: [
                    {
                        required: true,
                        message: '请填写税价合计',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    {
                        required: true,
                        message: '请选择币种',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '本位币为必填项',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ],
                // baseCurAcceptanceAmount: [
                //     {
                //         required: true,
                //         message: '验收金额(本位币)为必填项',
                //         trigger: 'blur'
                //     }
                // ],
                sourceOfRawMaterials: [
                    {
                        required: true,
                        message: '请选择原材料来源',
                        trigger: 'blur'
                    }
                ],
                freight: [
                    {
                        required: true,
                        message: '请输入服务费用',
                        trigger: 'blur'
                    }
                ]
            },
            auditState: {},
            auditParams: {
                // 审核
                billId: '',
                billType: '1016',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1016',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            acceptanceDetailsTabs: 'processingFee',
            childTabClass: '',
            processingFeeData: [], // 加工费
            finishedProductData: [], // 成品明细
            rawMaterialsData: [], // 原物资
            processingFeeDelData: [],
            finishedProductDelData: [],
            rawMaterialsDelData: [],
            serviceFeeData: [], // 服务费
            errorList: [], //控制导航栏感叹号的显示
            tabArr: [],
            errorProcessingFeeMsg: [], // 验收明细-加工费
            errorFinishedProductMsg: [], // 验收明细-成品明细
            errorRawMaterialsMsg: [], // 验收明细-原物资
            errorServiceFeeMsg: [], // 服务费用
            processingUnited: {
                materials: [],
                processingUnitId: ''
            },
            selectStockQuery: {
                orgId: '',
                unitId: '',
                keyWord: '',
                stockType: '1'
            },
            addRow: {
                amount: null,
                billId: '',
                changeType: 0,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                dtlId: '',
                invoiceNo: '',
                price: null,
                quantity: null,
                settlementUnitId: '',
                settlementUnitName: '',
                taxAmount: null,
                taxRate: null,
                totalAmount: null
            },
            isBaseCurRate: true,
            inStockList: [],
            selectStocked: '选择库存',
            jsdwData: {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: [0, 1, 2],
                supplierTypes: [],
                subcontractorTypes: [],
                businessTypes: []
            },
            jsdwIds: null,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            apportionedAverageUnitPrice: 0, // 分摊平均单价
            processingFeeAmountAll: 0, // 加工费总金额
            amountOfRawMaterialsAll: 0, // 原物资总金额
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            serviceFeeList: [], // 服务费用已选择数据
            rawMaterialsList: [], // 原物资已选数据
            yuanwuziQuery: {
                contractId: '',
                materialInfos: [
                    {
                        materialClassId: '',
                        materialId: '',
                        quantity: 0,
                        spec: '',
                        texture: '',
                        unit: '',
                        warehouseId: ''
                    }
                ],
                processingUnitId: ''
            },
            rawMaterialsSelects: false,
            selectFlag: false,
            tableHeadClass: 'cancelClass',
            isZhoucai: false
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 100 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        'formData.receivingType' () {
            // 如果收料类型为【普通加工】,原材料来源必选, 如果收料类型为【砼加工】,则非必选,并清除提示信息
            if (this.formData.receivingType) {
                this.$refs.formDataRef.clearValidate('sourceOfRawMaterials')
                this.formData.sourceOfRawMaterials = ''
            }
        },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        // 当成品明细数组的数据发生变化时,原物资选择库存下拉框的数据也需要跟着变化
        finishedProductData: {
            handler: function () {
                console.log(this.finishedProductData)
                this.inStockList = []
                this.finishedProductData.forEach(item => {
                    this.inStockList.push(...item.children.filter(itm => itm.changeType !== -1))
                })
                console.log(this.inStockList)
                // 遍历成品明细,看是否有物资类别为周材的
                this.isZhoucai = this.finishedProductData.some(item => {
                    return item.children.some(it => it.materialType === 1)
                })
            },
            deep: true
        },
        //给错误标签加上提醒
        errorList: newData => {
            console.log(newData)
            const tabs = document.querySelectorAll('.el-tabs__item')
            console.log(tabs)
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        rawMaterialsSelects () {
            if(this.rawMaterialsSelects) {
                this.tableHeadClass = 'tableHeadClass'
            } else {
                this.tableHeadClass = 'cancelClass'
            }
        },
    },

    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.selectStockQuery.orgId = this.orgId
        Promise.all([
            this.getBasicData(), //进入页面就获取基本信息数据
            this.getProcessingFeeData(), // 加工费
            this.getFinishedProductData(), // 成品明细
            this.getRawMaterialsData(), // 原物资
            this.getServeList(), // 服务费用
            this.getAttach(), // 获取附件列表
            this.getUnitInfo() // 获取按钮状态
        ]).then(() => {
            this.finishedProducAll()
        })

        // this.getDetailsData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            [
                'receivingMaterials',
                'processingFee',
                'finishedProductDetails',
                'rawMaterials'
            ],
            'transportationCharge',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag && arr.find(i => i === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(
                            item[0]
                        ).offsetHeight
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return (
                                    document.getElementById(x).offsetTop + 20
                                )
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                                    20 +
                                    prevHeight +
                                    document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop + 20
                        return itemTop
                    }
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 20 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 50 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 50 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.acceptanceDetailsTabs = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector(
                        '.childTab .el-tabs__nav'
                    )
                        ? document.querySelector('.childTab .el-tabs__nav')
                            .offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight =
                        document.getElementById(item[0]).offsetHeight +
                        document.getElementById(item[0]).nextSibling
                            .offsetHeight
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                                prevHeight +
                                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //获取基本信息数据
        async getBasicData () {
            let data = await processingRequest.getbasicInfo(this.billid)
            this.redFormData = this._.cloneDeep(data)
            if (data.redBillState == 3) {
                // 如果是3,说明进入该单据是红单进入到编辑页
                data.currency = this.currencyForm.find(
                    x => x.value == data.currencyId
                ).label
                this.formData = data
            } else {
                this.formData = data
            }
            this.yuanwuziQuery.processingUnitId = this.formData.processingUnitId
            this.yuanwuziQuery.contractId = this.formData.contractId

            // 开启加工验收金额(元)的监听
            this.$watch('formData.acceptanceAmount', () => {
                // 税额 = 加工验收金额 * 税率
                // alert(+this.formData.taxRate)
                this.formData.taxAmount = +(
                    +this.formData.acceptanceAmount *
                    (+this.formData.taxRate / 100 || 0)
                ).toFixed(2)
                // 税价合计 = 验收金额 + 税额
                this.formData.totalAmount = +(
                    (+this.formData.acceptanceAmount * 100 +
                        +this.formData.taxAmount * 100) /
                    100
                ).toFixed(2)
                // 验收金额(本位币) = 验收金额 * 本位币汇率
                this.formData.baseAcceptanceAmount =
                    +this.formData.acceptanceAmount *
                    +this.formData.baseCurRate
            })
            // 监听税率, 税额 = 不含税金额 * 税率
            this.$watch('formData.taxRate', () => {
                this.formData.taxAmount = +(
                    +this.formData.acceptanceAmount *
                    (+this.formData.taxRate / 100)
                ).toFixed(2)
            })
            // 监听税额
            this.$watch('formData.taxAmount', () => {
                // 税价合计 = 验收金额+税额
                this.formData.totalAmount = (
                    +(
                        +this.formData.acceptanceAmount * 100 +
                        +this.formData.taxAmount * 100
                    ) / 100
                ).toFixed(2)
            })

            // 监听服务费用税价合计
            this.$watch('serviceFeeData', () => {
                this.formData.freight = +(this.serviceFeeData.reduce((prev, c) => prev += (+c.totalAmount || 0), 0)).toFixed(2)
            }, { deep: true })
        },
        // 本位币汇率失去焦点时
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
            this.formData.baseCurAcceptanceAmount =
                +this.formData.acceptanceAmount * +this.formData.baseCurRate
        },
        // 当币种切换时,获取人民币汇率
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
        },
        // 点击加工单位后面的选择源单
        async processingUnitNameClick () {
            try {
                // this.setSelectedInfo({
                //     receivingType: this.formData.receivingType,
                //     processingUnited: this.processingUnited,
                //     orgId: this.orgId
                // })
                // openAppClient('/showSelectedData', '传参')
                let res

                if (this.formData.processingUnitId) {
                    // this.setSelectedInfo({

                    //     receivingType: this.formData.receivingType,
                    //     processingUnited: [JSON.stringify(this.processingUnited)]

                    // })
                    // openAppClient('/showSelectedData', '选择加工结果')
                    res = await processingRequest.selectSource(
                        {
                            receivingType: this.formData.receivingType
                        },
                        [JSON.stringify(this.processingUnited)]
                    )
                } else {
                    res = await processingRequest.selectSource(
                        {
                            receivingType: this.formData.receivingType
                        },
                        []
                    )
                }
                // let res = await processingRequest.selectSource(
                //     {
                //         receivingType: this.formData.receivingType
                //     },
                //     this.processingUnited
                // )
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择加工结果')

                // let res = await processingRequest.selectSource({
                //     orgId: this.orgId,
                //     receivingType: this.formData.receivingType,
                //     parentId: '',
                //     keyWord: ''
                // })
                //如果点击确定时，未选择数据，即数组是空的
                if (res.length < 1) {
                    this.clientPop('err', '请选择物资明细！')
                    // this.receivingTypeChange()
                    return
                }
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择结果')
                // 先判断所选择的数据是否都是同一个合同下的,如果不是同一个合同直接提示并且不执行后面操作
                let isSameContract = res.some(
                    item => res[0].contractId !== item.contractId
                )
                if (isSameContract) {
                    this.clientPop('err', '只能选择相同合同的物资,请重新选择!')
                    return
                }
                let data = res.find(item => item.parentId != 0)
                // 不能选择不同的合同做验收
                // if (
                //     this.formData.contractId &&
                //     this.formData.contractId !== data.contractId
                // ) {
                //     this.clientPop('err', '只能选择相同合同的物资,请重新选择!')
                //     return
                // }
                // 下面这个写法有问题
                // Object.assign(
                //     this.$data.processingUnited,
                //     this.$options.data().processingUnited
                // )
                if (
                    this.processingFeeData.length < 1 ||
                    !this.formData.processingUnitId
                ) {
                    await this.assignmentFun(data)
                    // 加工费
                    this.processingFeeData = await this.dataProcessingFun(res)
                    // 成品明细
                    this.finishedProductData = await this.dataProcessingFun(
                        res
                    )
                    // this.setSelectedInfo(this.finishedProductData)
                    // openAppClient('/showSelectedData', '选择结果')
                } else if (this.formData.contractId != data.contractId) {
                    this.clientPop(
                        'info',
                        '当前选择加工合同和原有加工合同不一致,若点击确定将覆盖原有基本信息和加工费,成品明细!',
                        () => {
                            this.jgdwChange()
                            this.assignmentFun(data)
                            this.acceptancePush(res)
                            this.finishedProducAll()
                            // this.processingFeeData =
                            //     await this.dataProcessingFun(res)
                            // this.finishedProductData =
                            //     await this.dataProcessingFun(res)
                        }
                    )
                } else {
                    this.assignmentFun(data)
                    this.acceptancePush(res)
                    this.finishedProducAll()
                }
                // this.processingFeeData.forEach(item => {
                //     // 计算加工费总金额
                //     this.processingFeeAmountAll = item.children.reduce((am, c) => am += (+c.amount || 0), 0)
                // })
                // // 计算成品明细的某些值
                // this.finishedProductData.forEach(item => {
                //     // this.formData.freight // 服务费总金额
                //     // this.apportionedAverageUnitPrice // 分摊平均单价
                //     // quantityAll: 成品明细总数量
                //     // 分摊平均单价 = 服务费总金额/成品明细总数量
                //     // 分摊服务费 = 分摊平均单价*数量
                //     // 计算分摊平均单价
                //     const quantityAll = item.children.reduce(
                //         (pre, c) => (pre += +c.quantity || 0),
                //         0
                //     )
                //     // 分摊平均单价 = 服务费总金额/成品明细总数量
                //     this.apportionedAverageUnitPrice =
                //         +this.formData.freight / +quantityAll

                //     item.children.forEach(i => {
                //         // 分摊服务费 = 分摊平均单价*数量
                //         i.apportionedFreight = (
                //             +this.apportionedAverageUnitPrice * +i.quantity
                //         ).toFixed(2)
                //         // 计算成品明细的金额 = 加工费总金额+原物资总金额+当前行分摊服务费
                //         i.amount = +this.processingFeeAmountAll + +this.amountOfRawMaterialsAll + i.apportionedFreight
                //         // 成品单价 = 金额/数量
                //         i.price = (+i.amount / +i.quantity).toFixed(2)
                //     })
                // })

            } catch (err) {
                alert(err.message)
            }
        },
        // 计算成品明细的各个关联值
        finishedProducAll () {
            this.processingFeeData.forEach(item => {
                const count = +(item.children.reduce((prev, c) => prev += (+c.amount || 0), 0)).toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            // 计算服务费用的总金额
            const freightSum = this.serviceFeeData.reduce((prev, c) => prev += (+c.amount || 0), 0)
            // 计算成品明细的总数量
            let quantityAll = 0
            this.finishedProductData.forEach(item => {
                quantityAll += +(item.children.reduce((prev, c) => prev += (+c.quantity || 0), 0))
            })
            // console.log('服务费总金额', freightSum)
            // console.log('成品明细总数量', quantityAll)
            // 分摊平均单价 = 服务费总金额/成品明细总数量
            if (+quantityAll) {
                this.apportionedAverageUnitPrice = +freightSum / +quantityAll
                // console.log('分摊平均单价', this.apportionedAverageUnitPrice)
            } else {
                this.apportionedAverageUnitPrice = 0
            }

            // 基本信息的加工验收金额
            let countSumC = 0
            this.finishedProductData.forEach(item => {
                // const counts = +item.children
                //     .reduce((prev, c) => prev += (+c.amount || 0), 0)
                //     .toFixed(2)
                // item.materialName = `金额小计： ${counts}`
                // countSumC += +counts
                // freightSum // 服务费总金额
                // this.apportionedAverageUnitPrice // 分摊平均单价
                // quantityAll: 成品明细总数量
                // 分摊平均单价 = 服务费总金额/成品明细总数量
                // 当前行分摊服务费 = 分摊平均单价*当前行数量

                // 与成品明细对应物资的加工费金额相加
                item.children.forEach(i => {
                    // 当前行分摊服务费 = 分摊平均单价*当前行数量
                    i.apportionedFreight = +(+this.apportionedAverageUnitPrice * +i.quantity).toFixed(2)
                    // 计算成品明细每行的金额 = 与当前行对应物资的加工费金额 + 与当前行对应物资的原物资金额 + 当前行分摊服务费
                    this.processingFeeData.forEach(item => {
                        item.children.forEach(it => {
                            if(it.materialId === i.materialId) {
                                i.amount = +(+it.amount + +i.apportionedFreight).toFixed(2)
                            }
                        })
                    })
                    // 成品明细每行的金额 = 与当前行对应物资的加工费金额 + 与当前行对应物资的原物资金额 + 当前行分摊服务费
                    this.rawMaterialsData.forEach(item => {
                        if(item.topClassId === i.materialId) {
                            const wuziSum = item.children.reduce((prev, c) => prev += (+c.amount || 0), 0)
                            i.amount = +(+wuziSum + +i.amount).toFixed(2)
                        }
                    })

                    // 成品单价 = 金额/数量
                    if (i.quantity) {
                        i.price = +(+i.amount / +i.quantity).toFixed(2)
                    }
                    if(i.changeType === 1) {
                        i.changeType = 1
                    }else if(i.changeType === -1) {
                        i.changeType = -1
                    }else {
                        i.changeType = 2
                    }
                })
                // this.setSelectedInfo(this.finishedProductData)
                // openAppClient('/showSelectedData', '选择结果')
                const count = +(item.children
                    .reduce((prev, c) => prev += (+c.amount || 0), 0))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSumC += +count
            })
            this.formData.acceptanceAmount = +(+countSumC).toFixed(2)
        },
        // 根据弹窗选择的数据给基本信息赋值
        async assignmentFun (data) {
            this.formData.processingUnitName = data.processingUnitName // 加工单位
            this.formData.processingUnitId = data.processingUnitId // 加工单位Id
            this.yuanwuziQuery.processingUnitId = data.processingUnitId
            this.formData.contractName = data.contractName // 加工合同
            this.formData.contractId = data.contractId // 加工合同ID
            this.yuanwuziQuery.contractId = data.contractId
            this.formData.purchaserId = data.purchasingPersonnelId // 采购人员id
            this.formData.purchaserName = data.purchasingPersonnelName // 采购人员名称
            this.formData.isIncludingProcessingFee =
                data.isIncludingProcessingFee
            try {
                // this.setSelectedInfo(data.contractId)
                // openAppClient('/showSelectedData', '传参')
                let res1 = await processingRequest.getcontractbasicInfo(
                    data.contractId
                )
                // this.setSelectedInfo(res1)
                // openAppClient('/showSelectedData', '选择结果')
                if (!res1.code) {
                    this.formData.taxRate = res1.taxRate // 税率,根据加工收料带入加工合同税率
                    this.formData.currency = res1.currencyName // 币种名称
                    this.formData.currencyId = res1.currencyId // 币种ID
                } else {
                    this.formData.taxRate = 0
                    this.formData.currency = '' // 币种名称
                    this.formData.currencyId = '' // 币种ID
                }
            } catch (err) {
                this.formData.taxRate = 0
                this.formData.currency = '' // 币种名称
                this.formData.currencyId = '' // 币种ID
            }
        },

        // 处理弹窗选择的数据格式
        async dataProcessingFun (res) {
            const newArr = []
            let obj = {}
            res.forEach(async item => {
                if (item.materialClassName && item.materialClassId) {
                    const topClassName = item.materialClassName.split('/')[0]
                    const topClassId = item.materialClassId.split('/')[0]
                    obj = {
                        topClassId,
                        topClassName,
                        customId: topClassId,
                        materialClassId: topClassId,
                        materialClassName: topClassName,
                        uuid: getUuid(),
                        totalAmount: null,
                        totalQuantity: null,
                        children: []
                    }
                    if (newArr.length < 1) {
                        newArr.push(obj)
                    } else {
                        let isParent = newArr.every(
                            itm => itm.topClassId !== topClassId
                        )
                        if (isParent) {
                            newArr.push(obj)
                        }
                    }

                    newArr.forEach(async its => {
                        if (
                            its.materialClassId ===
                            item.materialClassId.split('/')[0]
                        ) {
                            its.children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                billId: this.billid, //	验收ID
                                changeType: 1, //变更类型
                                dtlId: '', //验收明细ID
                                materialClassId: item.materialClassId
                                    .split('/')
                                    .slice(1)
                                    .join('/'), //物资类别id
                                materialClassName: item.materialClassName
                                    .split('/')
                                    .slice(1)
                                    .join('/'), // 物资类别名称
                                materialId: item.materialId, //物资id
                                materialName: item.materialName, //物资名称
                                sourceDtlId: item.dtlId, //源单明细id
                                spec: item.spec, //规格型号
                                texture: item.texture, //材质
                                unit: item.unit, //计量单位
                                warehouseId: item.warehouseId, //仓库id
                                warehouseName: item.warehouseName,
                                price: '', // 加工单价
                                processingReceiptDtlId: item.dtlId, // 加工收料明细id
                                amount: '', // 金额
                                quantity: item.unAcceptedQuantity, //数量
                                unacceptanceQuantity: item.unAcceptedQuantity, // 未验收数量
                                amortizationMonth: '', //摊销月
                                apportionedFreight: '', // 分摊服务费
                                materialType: item.materialType, //物资类型
                                totalAmortizationRatio: '' //总摊销比例(%)
                            })
                        }
                        this.processingUnited.materials.push({
                            materialClassId: item.materialClassId
                                .split('/')
                                .slice(1, 3)
                                .join('/'),
                            materialId: item.materialId,
                            texture: item.texture
                        })
                        // 统计小计
                        const count = +its.children
                            .reduce((prev, c) => (prev += +c.amount || 0), 0)
                            .toFixed(2)
                        its.materialName = `金额小计： ${count}`
                    })
                }
                // 生成dtlId
                for (let i = 0; i < newArr.length; i++) {
                    for (let m = 0; m < newArr[i].children.length; m++) {
                        newArr[i].children[m].dtlId =
                            await processingRequest.getUuid()
                    }
                }
                // this.setSelectedInfo(newArr)
                // openAppClient('/showSelectedData', '选择结果')
            })

            console.log(newArr)
            console.log(this.processingUnited)
            this.processingUnited.processingUnitId =
                this.formData.processingUnitId
            return newArr
        },
        async acceptancePush (res) {
            let newArr =  await this.dataProcessingFun(res)
            newArr.forEach(item => {
                const topClassIdRp = this.processingFeeData.every(
                    itm => itm.topClassId != item.topClassId
                )
                if (topClassIdRp) {
                    const a = this._.cloneDeep(item)
                    const b = this._.cloneDeep(item)
                    this.processingFeeData.push(a)
                    this.finishedProductData.push(b)
                } else {
                    const index = this.processingFeeData.findIndex(
                        its => its.topClassId == item.topClassId
                    )
                    item.children.forEach(it => {
                        const materialIdRp = this.processingFeeData[
                            index
                        ].children.every(
                            _it => _it.materialId != it.materialId
                        )
                        if (materialIdRp) {
                            const a = this._.cloneDeep(it)
                            const b = this._.cloneDeep(it)
                            this.processingFeeData[index].children.push(
                                a
                            )
                            this.finishedProductData[
                                index
                            ].children.push(b)
                        }
                    })
                }
            })
        },
        // 点击选择验收人员
        async acceptancerNameClick () {
            let data = await processingRequest.institutionalStaff()
            this.formData.acceptancerId = data[0].userId
            this.formData.acceptancerName = data[0].userName
        },
        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        contractNoClick () {
            // 弹出合同详细页面
            openAppClient(
                `/processingContractApplyShow?billid=${
                    this.formData.contractId
                }&isview=${true}`,
                '查看加工合同'
            )
        },

        // 收料类型变化后,
        receivingTypeChange () {
            this.formData.processingUnitName = ''
            this.formData.processingUnitId = ''
            this.yuanwuziQuery.processingUnitId = ''
            this.formData.contractName = ''
            this.formData.contractId = ''
            this.yuanwuziQuery.contractId = ''
            this.formData.purchaserName = ''
            this.formData.taxRate = ''
            this.formData.currency = ''
            this.formData.currencyId = ''
            this.formData.acceptanceAmount = ''
            this.formData.sourceOfRawMaterials = ''
            this.inStockList = []
            this.selectStocked = '选择库存'
            this.jgdwChange()
        },
        jgdwChange () {
            // 处理加工费表格数据
            for (let i = 0; i < this.processingFeeData.length; i++) {
                for (
                    let m = 0;
                    m < this.processingFeeData[i]['children'].length;
                    m++
                ) {
                    if (this.processingFeeData[i]['children'][m]['dtlId']) {
                        this.$set(
                            this.processingFeeData[i]['children'][m],
                            'changeType',
                            -1
                        )
                        this.$set(
                            this.processingFeeData[i]['children'][m],
                            'amount',
                            0
                        )
                    } else {
                        this.processingFeeData[i]['children'].splice(m, 1)
                        m--
                    }
                }
            }
            // 处理成品明细表格数据, 涉及后面会加入计算的分摊费和数量都需要置为0,否则影响后面数据准确性
            for (let i = 0; i < this.finishedProductData.length; i++) {
                for (
                    let m = 0;
                    m < this.finishedProductData[i]['children'].length;
                    m++
                ) {
                    if (this.finishedProductData[i]['children'][m]['dtlId']) {
                        this.$set(
                            this.finishedProductData[i]['children'][m],
                            'changeType',
                            -1
                        )
                        this.$set(
                            this.finishedProductData[i]['children'][m],
                            'amount',
                            0
                        )
                        this.$set(
                            this.finishedProductData[i]['children'][m],
                            'apportionedFreight',
                            0
                        )
                        this.$set(
                            this.finishedProductData[i]['children'][m],
                            'quantity',
                            0
                        )
                    } else {
                        this.finishedProductData[i]['children'].splice(m, 1)
                        m--
                    }
                }
            }
            this.formData.amount = 0
            // 处理原物资数据
            for (let i = 0; i < this.rawMaterialsData.length; i++) {
                for (
                    let m = 0;
                    m < this.rawMaterialsData[i]['children'].length;
                    m++
                ) {
                    if (this.rawMaterialsData[i]['children'][m]['dtlId']) {
                        this.$set(
                            this.rawMaterialsData[i]['children'][m],
                            'changeType',
                            -1
                        )
                        this.$set(
                            this.rawMaterialsData[i]['children'][m],
                            'amount',
                            0
                        )
                    } else {
                        this.rawMaterialsData[i]['children'].splice(m, 1)
                        m--
                    }
                }
            }
            // 服务费用也需要清空
            for (let i = 0; i < this.serviceFeeData.length; i++) {
                if (this.serviceFeeData[i]['dtlId']) {
                    this.$set(
                        this.serviceFeeData[i],
                        'changeType',
                        -1
                    )
                    this.$set(
                        this.serviceFeeData[i],
                        'totalAmount',
                        0
                    )
                    this.$set(
                        this.serviceFeeData[i],
                        'amount',
                        0
                    )
                } else {
                    this.serviceFeeData.splice(i, 1)
                    i--
                }
            }
            this.formData.freight = 0
            this.processingFeeDelData.push(...this.processingFeeData)
            this.finishedProductDelData.push(...this.finishedProductData)
            this.rawMaterialsDelData.push(...this.finishedProductData)
        },

        //获取验收明细-加工费
        async getProcessingFeeData () {
            let res = await processingRequest.getProcessingFeeData(this.billid)
            if (!Array.isArray(res)) return
            let countSum = 0
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = +item.children
                    .reduce((prev, c) => (prev += +c.amount || 0), 0)
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +count
            })
            this.processingFeeAmountAll = +countSum.toFixed(2)
            this.processingFeeData = res
        },
        //获取验收明细-成品明细
        async getFinishedProductData () {
            let res = await processingRequest.getFinishedProductData(
                this.billid
            )
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = +item.children
                    .reduce((prev, c) => (prev += +c.amount || 0), 0)
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.finishedProductData = res
            // 监听成品明细变化
            this.$watch('finishedProductData', () => {
                // 如果是砼加工的情况,需要自动带入原物资的数据
                if (this.formData.receivingType === 1) {
                    let arr = []
                    this.finishedProductData.forEach(item => {
                        arr = item.children.map(it => {
                            if(it.changeType !== -1) {
                                return {
                                    materialClassId: it.materialClassId,
                                    materialId: it.materialId,
                                    quantity: it.unacceptanceQuantity,
                                    spec: it.spec,
                                    texture: it.texture,
                                    unit: it.unit,
                                    warehouseId: it.warehouseId
                                }
                            }
                        })
                    })
                    this.yuanwuziQuery.materialInfos = arr
                    this.rawMaterialsFn()
                }
            }, { deep: true })
        },

        // 监听加工费数量
        quantityInput (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }

            if (
                +row.unacceptanceQuantity &&
                +row.quantity > +row.unacceptanceQuantity
            ) {
                this.clientPop(
                    'err',
                    `不能大于未验收数量${row.unacceptanceQuantity}`
                )
                row.quantity = +row.unacceptanceQuantity
                if (+row.amount && +row.quantity) {
                    row.price = +(+row.amount / +row.quantity).toFixed(2)
                }
            } else {
                if (+row.amount && +row.quantity) {
                    row.price = +(+row.amount / +row.quantity).toFixed(2)
                } else {
                    row.price = 0
                }
            }
            // 如果加工费的数量变化,成品明细的数量也要跟着变化成一样的
            let newArr = this.finishedProductData.map(item => {
                return [...item.children]
            })
            newArr.flat(Infinity).forEach(item => {
                if (row.materialId == item.materialId) {
                    item.quantity = row.quantity
                    if (item.changeType == 1) {
                        item.changeType = 1
                    } else {
                        item.changeType = 2
                    }
                }
            })
        },

        // 监听加工费金额
        amountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.quantity && +row.amount) {
                row.price = +(+row.amount / +row.quantity).toFixed(2)
            } else {
                row.price = 0
            }

            this.finishedProducAll()
        },
        // 成品明细-数量
        finishedProductQuantityInput (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (
                +row.unacceptanceQuantity &&
                +row.quantity > +row.unacceptanceQuantity
            ) {
                this.clientPop(
                    'err',
                    `不能大于未验收数量${row.unacceptanceQuantity}`
                )
                row.quantity = +row.unacceptanceQuantity
            }
            if (+row.amount && +row.quantity) {
                row.price = +(+row.amount / +row.quantity).toFixed(2)
            } else {
                row.price = 0
            }

            // 如果加工费的数量变化,成品明细的数量也要跟着变化成一样的
            let newArr = this.processingFeeData.map(item => {
                return [...item.children]
            })
            newArr.flat(Infinity).forEach(item => {
                if (row.materialId == item.materialId) {
                    item.quantity = row.quantity
                    if (item.changeType == 1) {
                        item.changeType = 1
                    } else {
                        item.changeType = 2
                    }
                }
            })
            // this.formData.freight // 服务费总金额
            // this.apportionedAverageUnitPrice // 分摊平均单价
            // quantityAll: 成品明细总数量
            // 分摊平均单价 = 服务费总金额/成品明细总数量
            // 分摊服务费 = 分摊平均单价*数量
            // this.finishedProductData.forEach(item => {
            //     const quantityAll = item.children.reduce(
            //         (pre, c) => (pre += +c.quantity || 0),
            //         0
            //     )
            //     this.apportionedAverageUnitPrice =
            //         +this.formData.freight / +quantityAll
            //     item.children.forEach(i => {
            //         i.apportionedFreight = (
            //             +this.apportionedAverageUnitPrice * +i.quantity
            //         ).toFixed(2)
            //         i.amount = +this.processingFeeAmountAll + +this.amountOfRawMaterialsAll + i.apportionedFreight
            //         i.price = (+i.amount / +i.quantity).toFixed(2)
            //     })
            // })
            this.finishedProducAll()
        },
        // 总摊销比例%
        totalAmortizationRatioBlur (row) {
            if (row.totalAmortizationRatio == 0) {
                row.totalAmortizationRatio = ''
            }
        },
        // 摊销月
        amortizationMonthBlur (row) {
            if (row.amortizationMonth == 0) {
                row.amortizationMonth = ''
            }
        },
        // 原物资-冲库存数量
        offsetInventoryQuantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (
                +row.receivedQuantity &&
                +row.offsetInventoryQuantity > +row.receivedQuantity
            ) {
                this.clientPop(
                    'err',
                    `不能大于领用数量${row.receivedQuantity}`
                )
                row.offsetInventoryQuantity = row.receivedQuantity

            }
            if(+row.offsetInventoryQuantity && +row.amount) {
                row.price = +(
                    +row.amount / +row.offsetInventoryQuantity
                ).toFixed(2)
            }else {
                row.price = 0
            }
        },
        // 原物资-金额
        ywzAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.offsetInventoryQuantity && +row.amount) {
                row.price = +(
                    +row.amount / +row.offsetInventoryQuantity
                ).toFixed(2)
            } else {
                row.price = 0
            }
            let countSum = 0
            this.rawMaterialsData.forEach(item => {
                const count = +item.children
                    .reduce((prev, c) => (prev += +c.amount || 0), 0)
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +count
            })
            this.amountOfRawMaterialsAll = +countSum.toFixed(2)
            this.finishedProducAll()
        },
        // 获取原物资的表格数据
        async getRawMaterialsData () {
            let res = await processingRequest.getRawMaterialsData(this.billid)
            // this.setSelectedInfo(res)
            // openAppClient('/showSelectedData', '选择结果')
            if (!Array.isArray(res)) return
            let countSum = 0
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.isChecked = false
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                    i.parentId = item.topClassId
                })
                const count = +item.children
                    .reduce((prev, c) => (prev += +c.amount || 0), 0)
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +count
            })
            this.amountOfRawMaterialsAll = +countSum.toFixed(2)
            this.rawMaterialsData = res
        },

        // 当收料类型为砼加工,选择加工单位后,根据选择的成品明细带出原物资的数据
        async rawMaterialsFn () {
            // this.setSelectedInfo(this.yuanwuziQuery)
            // openAppClient('/showSelectedData', '选择结果')
            let res = await processingRequest.rawMaterialsFn(this.yuanwuziQuery)
            console.log(res)
            // this.inStockList
            //   this.setSelectedInfo(res)
            // openAppClient('/showSelectedData', '选择结果')
            let obj = {}
            this.inStockList.forEach(itms => {
                obj = {
                    topClassId: itms.materialId,
                    topClassName: itms.materialName,
                    materialClassId: itms.materialId,
                    materialClassName: itms.materialName,
                    uuid: getUuid(),
                    totalAmount: null,
                    totalQuantity: null,
                    children: [],
                    isChecked: false,
                }
                if (this.rawMaterialsData.length < 1) {
                    this.rawMaterialsData.push(obj)
                } else {
                    let isPush = this.rawMaterialsData.every(
                        i => i.topClassId !== obj.topClassId
                    )
                    if (isPush) {
                        this.rawMaterialsData.push(obj)
                    }
                }
            })
            res.forEach(item => {
                const topClassId = item.materialClassId.split('/')[0]
                this.rawMaterialsData.forEach(its => {
                    if(its.topClassId === topClassId) {
                        item.rawMaterials.forEach(it => {
                            let result = {
                                uuid: getUuid(),
                                customId: getUuid(),
                                amount: 0, // 金额
                                billId: this.billid, //	验收ID
                                changeType: 1, //变更类型
                                dtlId: '', //原物资明细id
                                finishedGoodsDtlId: it.finishedGoodsDtlId,
                                materialClassId: it.materialClassId, //物资类别id
                                materialClassName: it.materialClassName, // 物资类别名称
                                materialId: it.materialId, //物资id
                                materialName: it.materialName, //物资名称
                                offsetInventoryQuantity: '', // 冲库存数量
                                price: '', // 采购单价
                                receivedQuantity: it.collectedQuantity, // 领用数量
                                sourceFinishedGoodsDtlId: '',
                                sourceMaterialsDtlId: '',
                                spec: it.spec, //规格型号
                                texture: it.texture, //材质
                                unit: it.unit, //计量单位
                                warehouseId: it.pickingWarehouseId, //仓库id
                                warehouseName: it.pickingWarehouseName,
                                parentId: its.topClassId,
                            }
                            if(its.children.length < 1) {
                            // 如果没有子级,直接添加
                                its.children.push(result)
                            }else {
                                const isPush = its.children.every(
                                    m => m.materialId !== result.materialId
                                )
                                if (isPush) {
                                    its.children.push(result)
                                } else {
                                    const sameArr = its.children.filter(
                                        n => n.materialId === result.materialId
                                    )
                                    const noPush = sameArr.some(
                                        i => i.changeType !== -1
                                    )
                                    if (!noPush) {
                                        its.children.push(result)
                                    }
                                }
                            }
                        })
                    }
                    // 统计小计
                    const count = +its.children
                        .reduce((prev, c) => (prev += +c.amount || 0), 0)
                        .toFixed(2)
                    its.materialName = `金额小计： ${count}`
                })
            })
            this.finishedProducAll()
        },

        // 原物资-选择库存
        async selectStock (obj1) {
            // obj1是选中的那条成品明细的数据
            console.log(obj1)
            // this.setSelectedInfo(obj1)
            // openAppClient('/showSelectedData', '选择结果')
            this.selectStocked = obj1.materialName
            this.selectStockQuery.unitId = this.formData.processingUnitId
            // this.selectStockQuery.unitId = '1503177344080867329'
            // this.selectStockQuery.orgId = '1439990097591140358'
            try{

                let data = await processingRequest.selectStock(
                    this.selectStockQuery
                )

                // this.setSelectedInfo(data)
                // openAppClient('/showSelectedData', '选择结果')

                let obj = {}
                let countSum = 0

                data.forEach(item => {
                // const topClassName = item.materialClassName.split('/')[0]
                // const topClassId = item.materialClassId.split('/')[0]
                    obj = {
                        topClassId: obj1.materialId,
                        topClassName: obj1.materialName,
                        // customId: obj1.materialId,
                        materialClassId: obj1.materialId,
                        materialClassName: obj1.materialName,
                        uuid: getUuid(),
                        totalAmount: null,
                        totalQuantity: null,
                        children: [],
                        isChecked: false,
                    }
                    if (this.rawMaterialsData.length < 1) {
                        this.rawMaterialsData.push(obj)
                    } else {
                        let isPush = this.rawMaterialsData.every(
                            i => i.topClassId !== obj1.materialId
                        )
                        if (isPush) {
                            this.rawMaterialsData.push(obj)
                        }
                    }
                    this.rawMaterialsData.forEach(its => {
                        let result = {
                            uuid: getUuid(),
                            customId: getUuid(),
                            billId: this.billid, //	验收ID
                            changeType: 1, //变更类型
                            dtlId: '', //原物资明细id
                            finishedGoodsDtlId: obj1.dtlId,
                            materialClassId: item.materialClassId, //物资类别id
                            materialClassName: item.materialClassName, // 物资类别名称
                            materialId: item.materialId, //物资id
                            materialName: item.materialName, //物资名称
                            offsetInventoryQuantity: '', // 冲库存数量
                            receivedQuantity: item.quantity, // 领用数量
                            spec: item.spec, //规格型号
                            texture: item.texture, //材质
                            unit: item.unit, //计量单位
                            warehouseId: item.warehouseId, //仓库id
                            warehouseName: item.warehouseName,
                            price: '', // 采购单价
                            amount: 0, // 金额
                            parentId: its.topClassId,
                        }
                        if(its.topClassId === obj1.materialId) {
                            if (its.children.length < 1) {
                                // 如果没有子级,直接添加
                                its.children.push(result)
                            } else  {
                                // 如果已经有子级了,如果有没有一样的子级,没有则添加,有还需要判断changeType为-1且changeType没有其他值的情况才添加
                                const isPush = its.children.every(
                                    m => m.materialId !== result.materialId
                                )
                                if (isPush) {
                                    its.children.push(result)
                                } else {
                                    const sameArr = its.children.filter(
                                        n => n.materialId === result.materialId
                                    )
                                    const noPush = sameArr.some(
                                        i => i.changeType !== -1
                                    )
                                    if (!noPush) {
                                        its.children.push(result)
                                    }
                                }
                            }
                        }

                        // 统计小计
                        const count = +its.children
                            .reduce((prev, c) => (prev += +c.amount || 0), 0)
                            .toFixed(2)
                        its.materialName = `金额小计： ${count}`
                        countSum += +count
                    })
                })
                this.amountOfRawMaterialsAll = +countSum.toFixed(2)
                this.finishedProducAll()
            }catch(err) {
                alert(err)
            }
        },

        // 原物资-删除
        rawMaterialsDelete (row) {
            this.clientPop('info', this.oneDeleteErr, () => {
                if (row.dtlId) {
                    // 如果有明细id,说明是已经存在后端数据库中的数据,已存在的数据,在删除时只能将changType设为-1
                    this.$set(row, 'changeType', -1)
                } else {
                    // 没有明细id,说明是刚新增的数据,直接在原数组中删除即可
                    this.rawMaterialsData.forEach(item => {
                        item.children.forEach((its, index) => {
                            if (this._.isEqual(its, row)) {
                                item.children.splice(index, 1)
                            }
                        })
                    })
                }
                row.amount = 0
                let countSum = 0
                this.rawMaterialsData.forEach(item => {
                    const count = +item.children
                        .reduce((prev, c) => (prev += +c.amount || 0), 0)
                        .toFixed(2)
                    item.materialName = `金额小计： ${count}`
                    countSum += +count
                })
                this.amountOfRawMaterialsAll = +countSum.toFixed(2)
                this.finishedProducAll()
            })
        },
        tableRowClassNameJ ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            if (row.children) {
                if (row.children.length < 1) {
                    return 'warning-row'
                } else {
                    let isDel = row.children.every(it => it.changeType === -1)
                    if (isDel) {
                        return 'warning-row'
                    }
                }
            }
            return ''
        },
        tableRowClassNameC ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            if (row.children) {
                if (row.children.length < 1) {
                    return 'warning-row'
                } else {
                    let isDel = row.children.every(it => it.changeType === -1)
                    if (isDel) {
                        return 'warning-row'
                    }
                }
            }
            return ''
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            if (row.children) {
                if (row.children.length < 1) {
                    return 'warning-row'
                } else {
                    let isDel = row.children.every(it => it.changeType === -1)
                    if (isDel) {
                        return 'warning-row'
                    }
                }
            }
            return ''
        },
        // 全选
        rawMaterialsSelectAll (selection) {
            this.rawMaterialsSelects = !this.rawMaterialsSelects

            this.splite(this.rawMaterialsData, this.rawMaterialsSelects)

            // 如果点击全选后,选中数据的长度和原始数组中父级加上changeType不等于-1的子级数据总数相等,就说明是全选选中,否则是全不选中
            let count = 0
            this.rawMaterialsData.forEach(item => {
                count++
                item.children.forEach(it => {
                    if(it.changeType !== -1) {
                        count++
                    }
                })
            })
            // console.log(count)
            let num = 0
            selection.forEach(item => {
                if(item.changeType) {
                    if(item.changeType !== -1) {
                        num++
                    }
                }else {
                    num++
                }
            })
            // console.log(selection)
            if(num === count) {
                this.rawMaterialsSelects = true
            }else {
                this.rawMaterialsSelects = false
            }

            // 如果全选按钮是选中状态,那么父级控制选中与否的字段isChecked就应该是true
            if(this.rawMaterialsSelects) {
                this.rawMaterialsData.forEach(i => {
                    i.isChecked = true
                })
            } else {
                this.rawMaterialsData.forEach(i => {
                    i.isChecked = false
                })
            }
            // 点击全选的时候,把已经删除的子级changType设置为选中,如果某个父级下面所有的子级都为-1,则需要将这个父级的isChecked设置为true
            this.rawMaterialsData.forEach(item => {
                item.children.forEach(it => {
                    if(it.changeType === -1) {
                        this.$refs.rawMaterialsTable.toggleRowSelection(it, true)
                    }
                })
                let isCheckedAllChildren = item.children.every(its => its.changeType === -1)
                if(isCheckedAllChildren) {
                    this.$refs.rawMaterialsTable.toggleRowSelection(item, true)
                    item.isChecked = true
                }

            })
        },
        splite (data, flag) {
            data.forEach(row => {
                this.$refs.rawMaterialsTable.toggleRowSelection(row, flag)
                if(row.children != undefined) {
                    this.splite(row.children, flag)
                }
            })
        },
        // 当用户手动勾选数据行的 Checkbox 时触发的事件
        selectRow (selection, row) {
            if(row.children) {
                if(row.isChecked) {
                    row.children.forEach(item => {
                        if(item.changeType !== -1) {
                            this.$refs.rawMaterialsTable.toggleRowSelection(item, false)
                        }
                    })
                    row.isChecked = false
                } else {
                    row.children.forEach(item => {
                        if(item.changeType !== -1) {
                            this.$refs.rawMaterialsTable.toggleRowSelection(item, true)
                        }
                    })
                    row.isChecked = true
                }

            }else {
                const _parentId = row.parentId
                let count = 0
                const target = this.rawMaterialsData.find(i => {
                    if(i.topClassId === _parentId) {
                        i.children.forEach(its => {
                            if(its.changeType !== -1) {
                                count++
                            }
                        })
                        return i
                    }
                })

                const _target = selection.filter(it => {
                    return (it.parentId === _parentId) && (it.changeType !== -1)
                })
                if(count === _target.length) {
                    this.$refs.rawMaterialsTable.toggleRowSelection(target, true)
                    target.isChecked = true
                } else {
                    this.$refs.rawMaterialsTable.toggleRowSelection(target, false)
                    target.isChecked = false
                }
            }

            // // 全选判断
            const isAll = this.rawMaterialsData.every(i => {
                return i.isChecked === true
            })
            if(isAll) {
                this.tableHeadClass = 'tableHeadClass'
                this.rawMaterialsSelects = true
            } else {
                this.tableHeadClass = 'cancelClass'
                this.rawMaterialsSelects = false
            }
            // console.log(selection)
        },
        // 复选框选中的数据
        rawMaterialsSelect () {
            this.rawMaterialsList = this.$refs.rawMaterialsTable.selection
        },
        // 点击批量删除
        rawMaterialsDeleteClick () {
            this.rawMaterialsList = this.rawMaterialsList.filter(item => {
                if(item.children) {
                    const isEmpty = item.children.every(i => {
                        return i.changeType === -1
                    })
                    return isEmpty ? false : true
                } else {
                    return item.changeType !== -1
                }
            })
            const length = this.rawMaterialsList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.rawMaterialsDeleteList
                )
            }
        },
        // 批量删除
        rawMaterialsDeleteList () {
            this.rawMaterialsList.filter(row => {
                if (row.dtlId) {
                    this.rawMaterialsData.forEach(item => {
                        const index = item.children.findIndex(
                            its => its.dtlId === row.dtlId
                        )
                        if(index !== -1) {
                            this.$set(item.children[index], 'changeType', -1)
                            this.$set(item.children[index], 'amount', 0)
                        }
                    })
                } else {
                    this.rawMaterialsData.forEach(item => {
                        item.children.forEach((its, index) => {
                            if (this._.isEqual(its, row)) {
                                item.children.splice(index, 1)
                            }
                        })
                    })
                }
            })
            this.$refs.rawMaterialsTable.clearSelection()
            let countSum = 0
            this.rawMaterialsData.forEach(item => {
                const count = +(item.children
                    .reduce((prev, c) => (prev += +c.amount || 0), 0))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
                countSum += +count
            })
            this.amountOfRawMaterialsAll = +countSum.toFixed(2)
            this.finishedProducAll()
        },

        // ---------------------------------服务费用-----------------------------------
        // 点击服务费用的新增行
        addRowClick () {
            this.serviceFeeData.push({
                amount: '',
                billId: '',
                changeType: 0,
                contractBillId: '',
                contractBillNo: '',
                contractBillType: 0,
                contractDtlId: '',
                contractDtlName: '',
                contractQuantity: '',
                dtlId: '',
                invoiceNo: '',
                price: '',
                quantity: '',
                settlementUnitId: '',
                settlementUnitName: '',
                sourceServiceFeeDtlId: '',
                taxAmount: '',
                taxRate: '',
                totalAmount: ''
            })
            console.log(this.serviceFeeData)
        },
        // 获取服务费用表格数据
        async getServeList () {
            let res = await processingRequest.getServeList(this.billid)
            if (Array.isArray(res)) {
                this.serviceFeeData = res
            }
        },
        // 合同编号
        async contractDialog (row, index) {
            let contracted = {
                contractId: row.contractBillId,
                contractType: row.contractBillType || 0
            }
            // this.setSelectedInfo(contracted)
            // openAppClient('/showSelectedData', '选择结果')
            let res = await processingRequest.getContract(
                { orgid: this.orgId, contractId: this.formData.contractId, contractType: '1' },
                contracted
            )
            // this.setSelectedInfo(res)
            // openAppClient('/showSelectedData', '选择结果')
            let result
            // 如果选择的是合同并且合同下有清单,则需带入合同下的清单
            if (res.list && res.list.length > 0) {
                result = res.list.map(item => {
                    return {
                        amount: null,
                        billId: this.billid,
                        changeType: 1,
                        contractBillId: res.contractId,
                        contractBillNo: res.contractNumber,
                        contractBillType: res.contractType,
                        contractDtlId: item.detailedId,
                        contractDtlName: item.name,
                        contractQuantity: item.quantity,
                        dtlId: '',
                        invoiceNo: '',
                        price: null,
                        quantity: item.quantity,
                        settlementUnitId: res.secondPartyId,
                        settlementUnitName: res.secondPartyName,
                        sourceServiceFeeDtlId: '',
                        taxAmount: 0,
                        taxRate: res.taxRate,
                        totalAmount: 0
                    }
                })
                // this.setSelectedInfo(result)
                // openAppClient('/showSelectedData', '处理后结果')
                // this.setSelectedInfo(this.serviceFeeData)
                // openAppClient('/showSelectedData', '原有数组数据')

                // 保证添加进去的数据在原有数组中没有才添加或者被替换,在合同中可通过清单ID判断是否有重复的
                let _arr = []
                result.forEach(item => {
                    const shouldPush = this.serviceFeeData.every(
                        it => item.contractDtlId !== it.contractDtlId
                    )
                    if (shouldPush) {
                        _arr.push(item)
                    } else {
                        // 找到了清单ID相同
                        const repeatArr = this.serviceFeeData.filter(
                            i => item.contractDtlId === i.contractDtlId
                        )
                        const noPush = repeatArr.some(
                            _its => _its.changeType !== -1
                        )
                        if (!noPush) {
                            _arr.push(item)
                        }
                    }
                })
                if (_arr.length !== 0) {
                    this.serviceFeeData.splice(index, 1, ..._arr)
                }
            } else {
                // 如果选择的合同没有清单
                result = {
                    amount: null,
                    billId: this.billid,
                    changeType: 1,
                    contractBillId: res.contractId,
                    contractBillNo: res.contractNumber,
                    contractBillType: res.contractType,
                    contractDtlId: '',
                    contractDtlName: '',
                    contractQuantity: '',
                    dtlId: '',
                    invoiceNo: '',
                    price: null,
                    quantity: null,
                    settlementUnitId: res.secondPartyId,
                    settlementUnitName: res.secondPartyName,
                    sourceServiceFeeDtlId: '',
                    taxAmount: 0,
                    taxRate: res.taxRate,
                    totalAmount: 0
                }
                // 保证添加进去的数据在原有数组中没有才添加
                const shouldPush = this.serviceFeeData.every(
                    it => it.contractBillId !== result.contractBillId
                )
                if (shouldPush) {
                    this.serviceFeeData.splice(index, 1, result)
                } else {
                    const repeatArr = this.serviceFeeData.filter(
                        i => i.contractBillId === result.contractBillId
                    )
                    const noPush = repeatArr.some(
                        _its => _its.changeType !== -1
                    )
                    if (!noPush) {
                        this.serviceFeeData.splice(index, 1, result)
                    }
                }
            }
            // 因为新添加的数据金额都是空,所以没必要去计算一次金额
            // this.formData.freight = this.serviceFeeData.reduce(
            //     (pre, c) => (pre += +c.amount || 0),
            //     0
            // )
        },

        // 结算单位
        async billingUnitDialog (row, index) {
            this.jsdwIds = row.settlementUnitId
            let res = await request.getBillingUnit(this.jsdwData, this.jsdwIds)
            let result = {
                amount: null,
                billId: this.billid,
                changeType: 1,
                contractBillId: '',
                contractBillNo: '',
                contractBillType: 0,
                contractDtlId: '',
                contractDtlName: '',
                contractQuantity: '',
                dtlId: '',
                invoiceNo: '',
                price: null,
                quantity: null,
                settlementUnitId: res.id,
                settlementUnitName: res.outerName,
                sourceServiceFeeDtlId: '',
                taxAmount: 0,
                taxRate: 0,
                totalAmount: 0
            }
            // 保证添加进去的数据在原有数组中没有才添加
            const shouldPush = this.serviceFeeData.every(
                it => it.settlementUnitId !== result.settlementUnitId
            )
            if (shouldPush) {
                this.serviceFeeData.splice(index, 1, result)
            } else {
                const repeatArr = this.serviceFeeData.filter(
                    i => i.settlementUnitId === result.settlementUnitId
                )
                const noPush = repeatArr.some(_its => _its.changeType !== -1)
                if (!noPush) {
                    this.serviceFeeData.splice(index, 1, result)
                }
            }
            // this.formData.freight = this.serviceFeeData.reduce(
            //     (pre, c) => (pre += +c.amount || 0),
            //     0
            // )
        },

        // 清单名称
        contractDtlNameBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 数量变化时
        quantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // 不能超过合同数量
            if (+row.contractQuantity) {
                if (+row.quantity > +row.contractQuantity) {
                    this.clientPop(
                        'err',
                        `不能超过合同数量${row.contractQuantity}`
                    )
                    row.quantity = row.contractQuantity
                }
            }
            if (+row.amount && +row.quantity) {
                row.price = +(+row.amount / +row.quantity).toFixed(2)
            } else {
                row.price = 0
            }
        },
        // 服务费用金额变化时
        amountFBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.amount && +row.quantity) {
                row.price = +(+row.amount / +row.quantity).toFixed(2)
            }
            if (+row.amount && +row.taxRate) {
                row.taxAmount = +(+row.amount * (+row.taxRate / 100)).toFixed(
                    2
                )
            } else {
                row.taxAmount = 0
            }
            if (+row.amount && +row.taxAmount) {
                row.totalAmount = +(
                    (+row.amount * 100 + +row.taxAmount * 100) /
                    100
                ).toFixed(2)
            } else {
                row.totalAmount = 0
            }
            this.formData.freight = +this.serviceFeeData
                .reduce((pre, c) => (pre += +c.totalAmount || 0), 0)
                .toFixed(2)
            // 服务费金额变化,引起分摊平均单价变化,从而引起成品明细里面的分摊服务费变化
            // this.finishedProductData.forEach(item => {
            //     const quantityAll = item.children.reduce(
            //         (pre, c) => (pre += +c.quantity || 0),
            //         0
            //     )
            //     this.apportionedAverageUnitPrice =
            //         +this.formData.freight / +quantityAll
            //     item.children.forEach(i => {
            //         i.apportionedFreight = (
            //             +this.apportionedAverageUnitPrice * +i.quantity
            //         ).toFixed(2)
            //         i.amount = +this.processingFeeAmountAll + +this.amountOfRawMaterialsAll + i.apportionedFreight
            //         i.price = (+i.amount / +i.quantity).toFixed(2)
            //     })
            // })
            this.finishedProducAll()
        },
        // 编号变化时
        invoiceNoBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 税率变化时
        taxRateBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.amount && +row.taxRate) {
                row.taxAmount = +(+row.amount * (+row.taxRate / 100)).toFixed(
                    2
                )
            } else {
                row.taxAmount = 0
            }
            if (+row.amount && +row.taxAmount) {
                row.totalAmount = +(
                    (+row.amount * 100 + +row.taxAmount * 100) /
                    100
                ).toFixed(2)
            } else {
                row.totalAmount = 0
            }
        },
        //税额变化时
        taxAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (+row.amount && +row.taxAmount) {
                row.totalAmount = +(
                    (+row.amount * 100 + +row.taxAmount * 100) /
                    100
                ).toFixed(2)
            } else {
                row.totalAmount = 0
            }
        },
        // 服务费用删除
        serviceFeeDelete (row, index) {
            this.clientPop('info', this.oneDeleteErr, () => {
                if (row.dtlId) {
                    // 如果有明细id,说明是已经存在后端数据库中的数据,已存在的数据,在删除时只能将changType设为-1
                    this.$set(row, 'changeType', -1)
                    this.$set(row, 'amount', 0)
                    this.$set(row, 'totalAmount', 0)
                } else {
                    // 没有明细id,说明是刚新增的数据,直接在原数组中删除即可
                    this.serviceFeeData.splice(index, 1)
                }
                this.formData.freight = +this.serviceFeeData
                    .reduce((pre, c) => (pre += +c.totalAmount || 0), 0)
                    .toFixed(2)
                this.finishedProducAll()
            })
            // this.finishedProductData.forEach(item => {
            //     const quantityAll = item.children.reduce(
            //         (pre, c) => (pre += +c.quantity || 0),
            //         0
            //     )
            //     this.apportionedAverageUnitPrice =
            //         +this.formData.freight / +quantityAll
            //     item.children.forEach(i => {
            //         i.apportionedFreight = (
            //             +this.apportionedAverageUnitPrice * +i.quantity
            //         ).toFixed(2)
            //         i.amount = +this.processingFeeAmountAll + +this.amountOfRawMaterialsAll + i.apportionedFreight
            //         i.price = (+i.amount / +i.quantity).toFixed(2)
            //     })
            // })
        },
        tableRowClassNameF ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        // 复选框选中的数据
        serviceFeeSelect (selection) {
            this.serviceFeeList = selection.filter(
                item => item.changeType !== -1
            )
        },
        // 点击批量删除
        serviceFeeDeleteClick () {
            const length = this.serviceFeeList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.serviceFeeDeleteList
                )
            }
        },
        // 批量删除
        serviceFeeDeleteList () {
            this.serviceFeeList.filter(row => {
                if (row.dtlId) {
                    const index = this.serviceFeeData.findIndex(item => {
                        return item.dtlId == row.dtlId
                    })
                    this.$set(this.serviceFeeData[index], 'changeType', -1)
                    this.$set(this.serviceFeeData[index], 'amount', 0)
                    this.$set(this.serviceFeeData[index], 'totalAmount', 0)
                } else {
                    this.serviceFeeData.forEach((item, index) => {
                        if (this._.isEqual(item, row)) {
                            this.serviceFeeData.splice(index, 1)
                        }
                    })
                }
            })
            this.$refs.serviceFeeTable.clearSelection()
            this.formData.freight = this.serviceFeeData.reduce(
                (pre, c) => (pre += +c.totalAmount || 0),
                0
            )
            this.finishedProducAll()
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            // const _arr = this.tabArr.flat(Infinity)
            // console.log(_arr)
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            console.log(num)
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置验收明细-加工费有错误时在表格上面显示的错误信息
        setErrorProcessingFee (msg) {
            let index = this.errorProcessingFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorProcessingFeeMsg.push(msg)
            }
        },
        // 设置验收明细-成品明细有错误时在表格上面显示的错误信息
        setErrorFinishedProductMsg (msg) {
            let index = this.errorFinishedProductMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorFinishedProductMsg.push(msg)
            }
        },
        // 设置验收明细-原物资有错误时在表格上面显示的错误信息
        setErrorRawMaterialsMsg (msg) {
            let index = this.errorRawMaterialsMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorRawMaterialsMsg.push(msg)
            }
        },
        // 设置服务费用有错误时在表格上面显示的错误信息
        setErrorServiceFeeMsg (msg) {
            let index = this.errorServiceFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorServiceFeeMsg.push(msg)
            }
        },
        // 保存基本信息
        basicInfoSave () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        if (this.formData.redBillState == 3) {
                            this.redFormData.remarks = this.formData.remarks
                        }
                        processingRequest
                            .basicInfoSave(
                                this.formData.redBillState == 3
                                    ? this.redFormData
                                    : this.formData
                            )
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },

        // 保存加工费
        saveProcessingFeeData () {
            // this.setSelectedInfo(this.finishedProductData)
            // openAppClient('/showSelectedData', '加工费保存数据')
            this.errorProcessingFeeMsg = []
            return new Promise((resolve, reject) => {
                this.processingFeeData.forEach(its => {
                    its.children.forEach(item => {
                        if (item.changeType !== -1) {
                            !item.materialClassName
                                ? this.setErrorProcessingFee('请填写物资类别')
                                : ''
                            !item.materialName
                                ? this.setErrorProcessingFee('请填写物资名称')
                                : ''
                            !item.unit
                                ? this.setErrorProcessingFee('请填写单位')
                                : ''
                            !item.warehouseName
                                ? this.setErrorProcessingFee('请填写仓库')
                                : ''

                            !item.quantity
                                ? this.setErrorProcessingFee('请填写数量')
                                : ''
                            item.price === '' ||
                            item.price === null ||
                            isNaN(item.price)
                                ? this.setErrorProcessingFee(
                                    '请填写加工单价(元)'
                                )
                                : ''
                            item.amount === '' ||
                            item.amount === null ||
                            isNaN(item.amount)
                                ? this.setErrorProcessingFee('请填写金额(元)')
                                : ''
                        }
                    })
                })
                console.log(this.errorProcessingFeeMsg)
                if (this.errorProcessingFeeMsg.length > 0) {
                    this.setError('receivingMaterials')
                    this.setError('processingFee')
                    reject('验收明细错误')
                    return
                } else {
                    this.processingFeeData.push(...this.processingFeeDelData)
                    processingRequest
                        .saveProcessingFeeData(this.processingFeeData)
                        .then(() => {
                            this.getProcessingFeeData() // 加工费
                            this.clearError('processingFee')
                            resolve()
                        })
                        .catch(err => {
                            this.errorProcessingFeeMsg[0] = err.message
                            this.setError('processingFee')
                            reject(err)
                        })
                }
            })
        },
        // 保存成品明细
        saveFinishedProductData () {
            // this.setSelectedInfo(this.finishedProductData)
            // openAppClient('/showSelectedData', '成品明细保存数据')
            this.errorFinishedProductMsg = []
            return new Promise((resolve, reject) => {
                this.finishedProductData.forEach(its => {
                    its.children.forEach(item => {
                        if (item.changeType !== -1) {
                            !item.materialClassName
                                ? this.setErrorFinishedProductMsg(
                                    '请填写物资类别'
                                )
                                : ''
                            !item.materialName
                                ? this.setErrorFinishedProductMsg(
                                    '请填写物资名称'
                                )
                                : ''
                            !item.unit
                                ? this.setErrorFinishedProductMsg('请填写单位')
                                : ''
                            !item.warehouseName
                                ? this.setErrorFinishedProductMsg('请填写仓库')
                                : ''

                            !item.quantity
                                ? this.setErrorFinishedProductMsg('请填写数量')
                                : ''
                            item.price === '' ||
                            item.price === null ||
                            isNaN(item.price)
                                ? this.setErrorFinishedProductMsg(
                                    '请填写成品单价(元)'
                                )
                                : ''
                            item.amount === '' ||
                            item.amount === null ||
                            isNaN(item.amount)
                                ? this.setErrorFinishedProductMsg(
                                    '请填写金额(元)'
                                )
                                : ''

                            // 下面两项如果为周材, 才是必填
                            if (item.materialType == 1) {
                                !item.totalAmortizationRatio
                                    ? this.setErrorFinishedProductMsg(
                                        '总摊销比例%'
                                    )
                                    : ''
                                !item.amortizationMonth
                                    ? this.setErrorFinishedProductMsg('摊销月')
                                    : ''
                            }
                            // 如果服务费用表格有数据的情况下,分摊服务费才是必填项
                            if (this.serviceFeeData.length > 0) {
                                let isData = false
                                isData = this.serviceFeeData.every(
                                    item => item.changeType === -1
                                )
                                if (!isData) {
                                    !item.apportionedFreight
                                        ? this.setErrorFinishedProductMsg(
                                            '请填写分摊服务费(元)'
                                        )
                                        : ''
                                }
                            }
                        }
                    })
                })
                console.log(this.errorFinishedProductMsg)
                if (this.errorFinishedProductMsg.length > 0) {
                    this.setError('finishedProductDetails')
                    reject('验收明细错误')
                    return
                } else {
                    this.finishedProductData.push(
                        ...this.finishedProductDelData
                    )
                    processingRequest
                        .saveFinishedProductData(this.finishedProductData)
                        .then(() => {
                            this.getFinishedProductData() // 成品明细
                            this.clearError('finishedProductDetails')
                            resolve()
                        })
                        .catch(err => {
                            this.errorFinishedProductMsg[0] = err.message
                            this.setError('finishedProductDetails')
                            reject(err)
                        })
                }
            })
        },
        // 保存原物资
        saveRawMaterialsData () {
            console.log(this.rawMaterialsData)
            this.errorRawMaterialsMsg = []
            return new Promise((resolve, reject) => {
                console.log(this.rawMaterialsData.length)
                this.rawMaterialsData.forEach(its => {
                    its.children.forEach(item => {
                        if (item.changeType !== -1) {
                            !item.materialClassName
                                ? this.setErrorRawMaterialsMsg('请填写物资类别')
                                : ''
                            !item.materialName
                                ? this.setErrorRawMaterialsMsg('请填写物资名称')
                                : ''
                            !item.unit
                                ? this.setErrorRawMaterialsMsg('请填写单位')
                                : ''
                            !item.warehouseName
                                ? this.setErrorRawMaterialsMsg('请填写仓库')
                                : ''

                            !item.receivedQuantity
                                ? this.setErrorRawMaterialsMsg('请填写领用数量')
                                : ''
                            !item.offsetInventoryQuantity
                                ? this.setErrorRawMaterialsMsg(
                                    '请填写冲库存数量'
                                )
                                : ''
                            item.price === '' ||
                            item.price === null ||
                            isNaN(item.price)
                                ? this.setErrorRawMaterialsMsg(
                                    '请填写采购单价（元）'
                                )
                                : ''
                            item.amount === '' ||
                            item.amount === null ||
                            isNaN(item.amount)
                                ? this.setErrorRawMaterialsMsg(
                                    '请填写金额（元）'
                                )
                                : ''
                        }
                    })
                    console.log(this.errorRawMaterialsMsg)
                })
                if (this.errorRawMaterialsMsg.length > 0) {
                    this.setError('rawMaterials')
                    reject('验收明细错误')
                    return
                } else {
                    // this.setSelectedInfo(this.rawMaterialsData)
                    // openAppClient('/showSelectedData', '选择结果')
                    this.rawMaterialsData.push(...this.rawMaterialsDelData)
                    processingRequest
                        .saveRawMaterialsData(this.rawMaterialsData)
                        .then(() => {
                            this.getRawMaterialsData() // 原物资
                            this.clearError('rawMaterials')
                            resolve()
                        })
                        .catch(err => {
                            this.errorRawMaterialsMsg[0] = err.message
                            this.setError('rawMaterials')
                            reject(err)
                        })
                }
            })
        },
        // 保存服务费用
        saveServiceFeeData () {
            this.errorServiceFeeMsg = []
            return new Promise((resolve, reject) => {
                // 检测必填项是否全部填写完毕
                this.serviceFeeData.forEach(item => {
                    if (item.changeType !== -1) {
                        !item.settlementUnitName
                            ? this.setErrorServiceFeeMsg('请填写结算单位')
                            : ''
                        !item.contractDtlName
                            ? this.setErrorServiceFeeMsg('请填写清单名称')
                            : ''
                        !item.quantity
                            ? this.setErrorServiceFeeMsg('请填写数量')
                            : ''
                        item.price === '' ||
                        item.price === null ||
                        isNaN(item.price)
                            ? this.setErrorServiceFeeMsg('请填写单价(元)')
                            : ''
                        item.amount === '' ||
                        item.amount === null ||
                        isNaN(item.amount)
                            ? this.setErrorServiceFeeMsg('请填写金额(元)')
                            : ''
                        item.totalAmount === '' ||
                        item.totalAmount === null ||
                        isNaN(item.totalAmount)
                            ? this.setErrorServiceFeeMsg('请填写税价合计(元)')
                            : ''
                    }
                })
                // this.setSelectedInfo(this.serviceFeeData)
                // openAppClient('/showSelectedData', '选择结果')
                if (this.errorServiceFeeMsg.length > 0) {
                    this.setError('transportationCharge')
                    reject('服务费用错误')
                    return
                } else {
                    // 如果必填项已全部填完,那么才发送保存服务费用的接口,如果报错依然需要定位到具体位置
                    processingRequest
                        .saveServiceFeeData(this.serviceFeeData)
                        .then(() => {
                            this.getServeList() // 服务费用
                            this.clearError('transportationCharge')
                            resolve()
                        })
                        .catch(err => {
                            this.errorServiceFeeMsg[0] = err.message
                            this.setError('transportationCharge')
                            reject(err)
                        })
                }
            })
        },

        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            // 汇总验收数量
            let count = 0
            let countSum = 0
            this.finishedProductData.forEach(item => {
                count = +item.children
                    .reduce((pre, c) => (pre += +c.quantity || 0), 0)
                    .toFixed(4)
                countSum += +count
            })
            this.formData.acceptanceQuantity = +countSum.toFixed(4)
            // 计算加工费的税额,后面加工入库结算需要用到
            this.processingFeeData.forEach(item => {
                item.children.forEach(it => {
                    it.taxAmount = +(it.amount * (this.formData.taxRate / 100)).toFixed(2)
                })
            })
            Promise.all([
                this.basicInfoSave(),
                this.saveProcessingFeeData(),
                this.saveFinishedProductData(),
                this.saveRawMaterialsData(),
                this.saveServiceFeeData()
            ])
                .then(() => {
                    // hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    // this.clientPop('err', '保存失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        submitReviewFn () {
            // 如果是砼加工是自动带入原物资数据(不能选择原库存),砼加工必带入原物资
            // 如果是普通加工,且原料来源是购买,必选原物资
            // 如果是普通加工,原料来源是自有,且成品明细中物资类别包含周材的,则必选原物资
            // ======================================字段代表意思========================================
            // this.formData.receivingType: 收料类型
            // this.formData.sourceOfRawMaterials: 原材料来源
            // =====================================================
            // 查询原物资表格中是否有数据
            let isData
            if (this.rawMaterialsData.length > 0) {
                let arr = []
                this.rawMaterialsData.forEach(item => {
                    let isData = item.children.every(
                        its => its.changeType === -1
                    )
                    arr.push(isData)
                })
                isData = arr.every(i => i === true)
            } else {
                isData = true
            }

            // 查询成品明细中是否包含周材
            let isZhouCai = this.finishedProductData.some(item => {
                item.materialClassName === '周转材料'
            })
            // console.log(this.formData.receivingType === 1 && isData)
            // console.log(this.formData.sourceOfRawMaterials === 1 && isData)
            // console.log(this.formData.sourceOfRawMaterials === 2 && isZhouCai && isData)

            if (
                (this.formData.receivingType === 1 && isData) ||
                (this.formData.sourceOfRawMaterials === 1 && isData) ||
                (this.formData.sourceOfRawMaterials === 2 &&
                    isZhouCai &&
                    isData)
            ) {
                this.clientPop(
                    'err',
                    `请再次确认原材料的来源是购买还是自有。
                ▷若是购买，则必须选择原材料，以冲抵原材料借方收入账；
                ▷若是自有，无需选择原材料，可在【基本信息】将原材料来源选择为自有。`
                )
                return false
            } else {
                return true
            }
        },
        // 提交审核
        submitReview () {
            showLoading()
            this.errorList = []
            // 汇总验收数量
            let count = 0
            let countSum = 0
            this.finishedProductData.forEach(item => {
                count = +item.children
                    .reduce((pre, c) => (pre += +c.quantity || 0), 0)
                    .toFixed(4)
                countSum += +count
            })
            this.formData.acceptanceQuantity = +countSum.toFixed(4)
            // 计算加工费的税额,后面加工入库结算需要用到
            this.processingFeeData.forEach(item => {
                item.children.forEach(it => {
                    it.taxAmount = +(it.amount * (this.formData.taxRate / 100)).toFixed(2)
                })
            })
            Promise.all([
                this.basicInfoSave(),
                this.saveProcessingFeeData(),
                this.saveFinishedProductData(),
                this.saveRawMaterialsData(),
                this.saveServiceFeeData()
            ])
                .then(() => {
                    // 需要验证基本信息中税价合计和服务费用两者不能同时为0
                    if(this.formData.totalAmount == 0 && this.formData.freight == 0) {
                        this.clientPop('err', '税价合计和服务费用，两者不可同时为0。')
                        return
                    }
                    let isSubmit = this.submitReviewFn()
                    if (isSubmit) {
                        request
                            .commitAudit(this.auditParams)
                            .then(() => {
                                this.clientPop(
                                    'suc',
                                    '提交成功',
                                    this.handleClose
                                )
                            })
                            .catch(() => {
                                // this.clientPop('err', '提交失败', () => {
                                this.scorllError()
                                // })
                            })
                    }
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.scorllError()
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 撤销审核
        undoAudit () {
            showLoading()
            request
                .undoAudit(this.auditParams)
                .then(() => {
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        basicInfoDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    processingRequest
                        .basicInfoDelete(this.billid)
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },

        // --------------------------------下面按钮--------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await request.getCurrentUnitInfo(
                this.auditParams
            )
        },
        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.basicInfoDelete() // 删除
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon')) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        //提交
        submit () {},
        //保存
        save () {},
        ctDelete () {
            showPromptPop(
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。'
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/materialsettle/processingAcceptance/delete',
                    params: {
                        id: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('./processCheck')
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        handleClose () {
            hideLoading()
            this.$router.replace('/processCheck')
        },

        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //日期转换格式
        getTime (dt) {
            var year = dt.getFullYear() //年
            var month = dt.getMonth() + 1 //月
            var date = dt.getDate() //日
            month = month < 10 ? '0' + month : month
            date = date < 10 ? '0' + date : date
            var str = year + '-' + month + '-' + date
            return str
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }
    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}
.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
::v-deep .drp {
    .el-button--small {
        border-radius: 3px;
        margin-right: 10px;
        padding: 7px 15px !important;
    }
}
::v-deep.el-table .warning-row {
    display: none;
}
::v-deep .el-table__fixed {
    height: 100% !important;
}
.tableHeadClass {
        ::v-deep .el-checkbox__inner{
            background: #2f62d7 !important;
        }
}
.cancelClass {
        ::v-deep .el-checkbox__inner {
        background: #fff !important;
        }
}
</style>
